package com.javaee.ejb.jms;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import com.javaee.ejb.entity.ConversationMessage;
import com.javaee.ejb.jms.remote.ConversationMessageQueueBrowserRemote;
import com.javaee.ejb.session.remote.ConversationMessageManagerRemote;

import javax.ejb.EJB;
import javax.ejb.Stateful;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueReceiver;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * Session Bean implementation class ConversationMessageQueueBrowser
 */
@Stateful
public class ConversationMessageQueueBrowser implements
		ConversationMessageQueueBrowserRemote {

	@EJB
	private ConversationMessageManagerRemote messageManager;

	private QueueConnectionFactory connectionFactory;
	private Queue queue;

	/**
	 * Default constructor.
	 */
	public ConversationMessageQueueBrowser() {
		try {
			InitialContext context = new InitialContext();
			connectionFactory = (QueueConnectionFactory) context.lookup("JQCF");
			queue = (Queue) context.lookup("sampleQueue");
			context.close();
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public List<ConversationMessage> getLastMessage(int conversationId,
			int nbMessageMax) {
		// Recuperation des derniers messages presents dans la file
		try {
			QueueConnection connection = connectionFactory
					.createQueueConnection();
			QueueSession session = connection.createQueueSession(false,
					Session.DUPS_OK_ACKNOWLEDGE);

			QueueBrowser browser = session.createBrowser(queue);

			List<ObjectMessage> lastObjectMessageList = new ArrayList<ObjectMessage>();

			for (Enumeration msgs = browser.getEnumeration(); msgs
					.hasMoreElements();) {
				ObjectMessage objMsg = (ObjectMessage) msgs.nextElement();
				ConversationMessage message = (ConversationMessage) objMsg
						.getObject();

				if (message.getConversation().getId() == conversationId) {
					// Ajout du message a la liste
					lastObjectMessageList.add(objMsg);
				}
			}

			if (lastObjectMessageList.size() > nbMessageMax) {
				// Pour ne garder que les nbMessageMax derniers message de la
				// file
				QueueReceiver receiver;
				connection.start();
				for (int i = 0; i < lastObjectMessageList.size() - nbMessageMax; i++) {
					// Enregistrement de messages dans la base de donnees
					messageManager
							.saveConversationMessage((ConversationMessage) lastObjectMessageList
									.get(i).getObject());

					// Consommation du message
					receiver = session.createReceiver(queue, "JMSMessageID='"
							+ lastObjectMessageList.get(i).getJMSMessageID()
							+ "'");
					receiver.receiveNoWait();
				}
				connection.stop();
			}

			browser.close();
			connection.close();

			// Recuperation des nbMessageMax derniers messages de la file
			List<ConversationMessage> lastMessageList = new ArrayList<ConversationMessage>();
			for (int i = lastObjectMessageList.size() < nbMessageMax ? 0
					: lastObjectMessageList.size() - nbMessageMax; i < lastObjectMessageList
					.size(); i++) {
				lastMessageList.add((ConversationMessage) lastObjectMessageList
						.get(i).getObject());
			}

			return lastMessageList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
